using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Imaging;
using System.Threading;
using UltimateDefend.Properties;



namespace UltimateDefend
{
    public partial class ArcadeFrm : Form
    {
        Graphics g, g1;
        Bitmap buff;
        Thread game;
        public static ILevel CurrentLevel;

        /// <summary>
        /// test animation
        /// </summary>

        //luu cac thao tac cua nguoi dung
        private bool IsBuild;
        //private bool IsSell;
        //private bool IsUpgrade;
        //private bool IsMap;
        private bool IsMouseMove;

        private bool IsBack;
               

        private ITower m_CurrTower;     //luu tower hien hanh
       
        private Point m_CurrPoint;      //luu diem hien tai nguoi dung dang chon
        private Point pAccept;          //luu diem build tower

        private IMap map;               //luu ban do su dung        

        private int m_iSelectedTower;   //luu index cua tower dang duoc nguoi dung chon
        private IAnimation animation = null;

        public ArcadeFrm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Khoi tao cac gia tri trong khi load form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ArcadeFrm_Load(object sender, EventArgs e)
        {            
            g = CreateGraphics();

            //// Tao bitmap buffer
            //buff = new Bitmap(ClientRectangle.Width, ClientRectangle.Height);

            //khoi tao trang thai dau tien
            this.IsBuild = false;
            //this.IsMap = false;
            //this.IsSell = false;
            //this.IsUpgrade = false;
            this.IsMouseMove = false;
            this.IsBack = false;

            map = new MapLevel1();
            buff = new Bitmap(ClientRectangle.Width, ClientRectangle.Height);
            map.LoadMap(this.buff);

            this.m_iSelectedTower = -1;
                       
        }

        /// <summary>
        /// Don dep vung nho khi dong form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ArcadeFrm_Closing(object sender, CancelEventArgs e)
        {
            g.Dispose();
            g1.Dispose();
        }


        /// <summary>
        /// Vong lap cap nhat do hoa cho form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timerLoop_Tick(object sender, EventArgs e)
        {
            // Draw Sprite ********************************
            g1 = Graphics.FromImage(buff);

            //ve lai bmpBuff tu bmp chua ban do ban dau
            g1.DrawImage(map.BitmapMap, 0, 0);

            // Ve creeps bang ham nay
            DrawCreeps();

            foreach (ITower tmpTower in map.ListTower)
            {
                if (tmpTower.Animation != null)
                {
                    animation = tmpTower.Animation;
                    g1.DrawImage(animation.BitmapDisplay, new Rectangle(animation.CurrPoint.X, animation.CurrPoint.Y, animation.Width, animation.Height), 0, 0, animation.Width, animation.Height, GraphicsUnit.Pixel, animation.ImgAtt);                    
                }
            }

            if (CurrentLevel.Result == ILevel.LevelResult.Win)
            {
                CurrentLevel.Abort();
                //MessageBox.Show("Win"); ==> gay ra loi stack overflow
                // Chuyen sang man ke tiep
                timerLoop.Enabled = false;
            }
            else if (CurrentLevel.Result == ILevel.LevelResult.Lose)
            {
                CurrentLevel.Abort();
                //MessageBox.Show("Lose");
                // Hien thi game over
                timerLoop.Enabled = false;
            }

            g1.Dispose();
            this.Invalidate();                       
        }


        /// <summary>
        /// Ham dung de ve creep, transparent, cap nhat theo timer
        /// </summary>
        private void DrawCreeps()
        {
            foreach (IEnemy enemy in CurrentLevel.EnemyGroup)
            {
                // Kiem tra creep co dang chay hay khong, neu chua chay thi ko ve
                if (!enemy.IsRunning)
                    continue;
                // Kiem tra creep da chet chua
                // Neu thoa, thi khong ve creep nay
                if (enemy.IsDeath())
                    // ve~ creep chet
                    continue;

                // Kiem tra creep de ve dich chua
                if (enemy.IsFinish())
                    continue;


                enemy.GetTransparentColor();
                // Ve creep len buffer
                g1.DrawImage(enemy.Display, enemy.GetFrame(), 0, 0, enemy.XFrame, enemy.YFrame, GraphicsUnit.Pixel, enemy.imageAttribute);

            }
        }

        private void ArcadeFrm_KeyDown(object sender, KeyEventArgs e)
        {
            if ((e.KeyCode == System.Windows.Forms.Keys.Up))
            {
                // Rocker Up
                // Up
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.Down))
            {
                // Rocker Down
                // Down
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.Left))
            {
                // Left
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.Right))
            {
                // Right
            }
            if ((e.KeyCode == System.Windows.Forms.Keys.Enter))
            {
                // Enter
                //CurrentLevel
                timerLoop.Enabled = false;

                // Close form
                Close();
            }

        }

        /// <summary>
        /// Bat dau khoi tao
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timerGame_Tick(object sender, EventArgs e)
        {
            timerGame.Enabled = false;

            System.Xml.XmlTextReader levelData = new System.Xml.XmlTextReader(LoadFrm.startup + "\\Engine\\level.xml");

            CurrentLevel = new Level1(levelData);
            // Anh xa anchors point sang man hinh thiet bi
            CurrentLevel.ConvertToFullScreen(ClientRectangle.Width - 40, ClientRectangle.Height - 45);

            levelData.Close();

            game = new Thread(new ThreadStart(CurrentLevel.Start));
            // Bat dau man choi
            game.Start();

            timerLoop.Enabled = true;
        }

        private void btnBuild_Click(object sender, EventArgs e)
        {
            //ngung hoat dong cua quan linh lai
            timerLoop.Enabled = false;

            //this.IsUpgrade = false;
            this.IsBuild = true;
            //this.IsSell = false;
            //this.IsMap = false;

            //show dialog build
            BuildFrm frm = new BuildFrm();
            frm.ShowDialog();

            //lay ra tower nguoi dung dang chon
            this.m_CurrTower = frm.Tower;

            //load len man hinh cho nguoi dung biet nhung vi tri co the xay tower            
            Graphics g = Graphics.FromImage(this.buff);

            //ve lai man hinh grass luc dau khi chua co tree
            g.DrawImage(map.BitmapMap, new Rectangle(0, 0, ClientRectangle.Width, ClientRectangle.Height), new Rectangle(0, 0, map.BitmapMap.Width,map.BitmapMap.Height), GraphicsUnit.Pixel);

            //ve lai ban do (co danh dau cac vi tri co the build tower)
            map.RefreshMap(buff);

            //huy graphics
            g.Dispose();

            //ve lai man hinh
            this.Invalidate();
        }

        private void btnSell_Click(object sender, EventArgs e)
        {
            //this.IsUpgrade = false;
            this.IsBuild = false;
            //this.IsSell = true;
            //this.IsMap = false;

            //khong xet move move
            this.IsMouseMove = false;

            //ban tower
            if (this.m_iSelectedTower != -1)
            {
                //pha huy tower
                map.ListTower[this.m_iSelectedTower].IsDestroy = true;
                //loai bo tower khoi list
                map.RemoveTower(this.m_iSelectedTower);

                this.m_iSelectedTower = -1;
                this.Invalidate();
            }

            //cho quan linh hoat dong lai
            timerLoop.Enabled = true;
        }

        private void btnUpgrade_Click(object sender, EventArgs e)
        {
            //cho quan linh ngu hoat dong
            timerLoop.Enabled = false;

            //this.IsUpgrade = true;
            this.IsBuild = false;
            //this.IsSell = false;
            //this.IsMap = false;

            this.IsMouseMove = false;

            //show dialog upgrade
            BuildFrm frm = new BuildFrm();
            frm.ShowDialog();

            //ve hien thi len tower level moi
            if (this.m_iSelectedTower != -1)
            {
                ITower tower = frm.Tower;
                //luu lai vi tri cua tower cu cho tower moi
                tower.Position = map.ListTower[this.m_iSelectedTower].Position;

                //huy tower cu
                map.ListTower[this.m_iSelectedTower].IsDestroy = true;
                //loai bo tower cu
                map.RemoveTower(this.m_iSelectedTower);
                               
                //khoi dong cho tower moi
                tower.Start(ref CurrentLevel.creeps);
                //them vao tower moi tai vi tri cu
                map.AddTower(tower);

                this.m_iSelectedTower = -1;
                this.Invalidate();                
            }

            timerLoop.Enabled = true;
        }

        private void ArcadeFrm_MouseDown(object sender, MouseEventArgs e)
        {
            this.m_CurrPoint.X = e.X;
            this.m_CurrPoint.Y = e.Y;
            this.m_iSelectedTower = map.IsInListTower(this.m_CurrPoint);
            this.Invalidate();

        }

        private void ArcadeFrm_MouseMove(object sender, MouseEventArgs e)
        {
            //chi xu ly khi dang build
            if (IsBuild)
            {
                //nguoi dung dang di chuyen mouse
                this.IsMouseMove = true;

                //luu lai diem nguoi dung dang di chuyen mouse
                this.m_CurrPoint = new Point(e.X, e.Y);

                //ve lai man hinh
                this.Invalidate();
            }

        }

        private void ArcadeFrm_MouseUp(object sender, MouseEventArgs e)
        {
            //chi xet khi dang build tower
            if (IsBuild)
            {
                if (this.m_CurrTower.CanBuild(map, this.m_CurrPoint, 1000))
                {
                    btnMap.Visible = true;

                    //luu lai vi tri co the build tower
                    pAccept = this.m_CurrPoint;
                }
                else
                {
                    btnMap.Visible = false;
                }
            }
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            if (IsMouseMove)
            {
                Bitmap bmpTmp = new Bitmap(this.buff);

                if (this.m_CurrTower.CanBuild(map, this.m_CurrPoint, 1000))
                {
                    this.m_CurrTower.DrawTower(bmpTmp, true, Color.Green, this.m_CurrPoint);
                }
                else
                {
                    this.m_CurrTower.DrawTower(bmpTmp, true, Color.Yellow, this.m_CurrPoint);
                }

                //ve man hinh
                e.Graphics.DrawImage(bmpTmp, 0, 0);

                //huy bien bitmap tam
                bmpTmp.Dispose();
            }
            else
            {
                if (this.m_iSelectedTower != -1)
                {
                    map.SeletedTower(this.m_iSelectedTower);
                }
                else
                {
                    map.SeletedTower(-1);
                }

                map.RefreshMap(this.buff);

                //ve man hinh
                e.Graphics.DrawImage(this.buff, 0, 0);
            }            
        }

        protected override void OnPaintBackground(PaintEventArgs e)
        {
            if (!this.IsBack)
            {
                this.IsBack = true;
            }
        }

        private void btnMap_Click(object sender, EventArgs e)
        {
            if (IsBuild)
            {
                //this.IsUpgrade = false;
                this.IsBuild = false;
                //this.IsSell = false;
                //this.IsMap = true;

                this.IsMouseMove = false;

                //ve tower tai day va add tower vao                             

                ITower tmpTower = this.m_CurrTower;

                //build tower tai vi tri pAccept
                if (tmpTower.Build(map, this.buff, pAccept, 1000) > 0)
                {
                    //khoi dong cho tower
                    tmpTower.Start(ref CurrentLevel.creeps);
                    //them tower moi vao ban do
                    map.AddTower(tmpTower);

                }

                //ve lai man hinh
                this.Invalidate();

                this.IsBuild = false;

                //cho quan linh hoat dong
                timerLoop.Enabled = true;
            }
        }
    }
}